package com.tbit.main.constant;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.tbit.main.pojo.Host;
import com.tbit.main.util.LogUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 服务器
 *
 * @author Leon
 * 2020年6月5日 上午10:30:44
 */
public class HostConstant {
    public static Map<String, Host> hostMap = new HashMap<String, Host>();

    public static Host getHost(String name) throws NacosException, InterruptedException {
        Map<String, Host> hostMap = new HashMap<String, Host>();

        //Properties props = new Properties();
        try {
            //props.load(new InputStreamReader(HostConstant.class.getClassLoader().getResourceAsStream("host.properties"), "UTF-8"));
            String serverAddr = "192.168.1.174:8848";
            String dataId = "uqbike-maintain-host.yaml";
            String group = "uqbike-maintain";

            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);
            configService.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("recieve:" + configInfo);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });

            boolean isPublishOk = configService.publishConfig(dataId, group, "content");
            System.out.println(isPublishOk);

            Thread.sleep(3000);
            content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);

            boolean isRemoveOk = configService.removeConfig(dataId, group);
            System.out.println(isRemoveOk);
            Thread.sleep(3000);

            content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);
            Thread.sleep(300000);


            for (String key : properties.stringPropertyNames()) {
                hostMap.put(key, new Host(key, properties.getProperty(key)));
            }
        } catch (Exception e) {
            LogUtil.warn("加载服务器配置文件失败");
        }

        return hostMap.get(name);
    }

    public static void main(String[] args) throws NacosException, InterruptedException {
        System.out.println(getHost("优驱出行"));
    }

}
